/*
Copyright 2017 yangchong211（github.com/yangchong211）

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.yc.video.ui.view;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.CommonEventSupport;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;

import com.yc.video.ResourceTable;
import com.yc.video.bridge.ControlWrapper;
import com.yc.video.config.ConstantKeys;
import com.yc.video.tool.PlayerUtils;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2017/11/9
 *     desc  : 顶部标题栏视图
 *     revise:
 * </pre>
 */
public class CustomTitleView extends StackLayout implements InterControlView,
    Component.ClickedListener, Component.BindStateChangedListener, Animator.StateChangedListener {
    private Context mContext;
    private ControlWrapper mControlWrapper;
    private DirectionalLayout mLlTitleContainer;
    private Image mIvBack;
    private Text mTvTitle;
    private Image mIvBattery;
    private Text mTvSysTime;

    private BatteryReceiver mBatteryReceiver;
    private boolean mIsRegister; // 是否注册BatteryReceiver

    public CustomTitleView(Context context) {
        super(context);
        init(context);
    }

    public CustomTitleView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomTitleView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        setVisibility(Component.HIDE);
        Component component = LayoutScatter.getInstance(mContext).parse(
            ResourceTable.Layout_custom_video_player_top, this, true);
        initFindViewById(component);
        initListener();

        // 电量
        MatchingSkills matchingSkills = new MatchingSkills();
        CommonEventSubscribeInfo info = new CommonEventSubscribeInfo(matchingSkills);
        mBatteryReceiver = new BatteryReceiver(info, mIvBattery);
    }

    private void initFindViewById(Component component) {
        mLlTitleContainer = (DirectionalLayout) component.findComponentById(ResourceTable.Id_ll_title_container);
        mIvBack = (Image) component.findComponentById(ResourceTable.Id_iv_back);
        mTvTitle = (Text) component.findComponentById(ResourceTable.Id_tv_title);
        mIvBattery = (Image) component.findComponentById(ResourceTable.Id_iv_battery);
        mTvSysTime = (Text) component.findComponentById(ResourceTable.Id_tv_sys_time);
    }

    private void initListener() {
        mIvBack.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        if (component == mIvBack) {
            // 点击返回键
            Ability ability = PlayerUtils.scanForActivity(getContext());
            if (ability != null && mControlWrapper.isFullScreen()) {
                ability.setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
                ControlWrapper.defaultValue();
                mControlWrapper.stopFullScreen();
                return;
            }

            // 如果不是全屏模式，则直接关闭页面activity
            if (PlayerUtils.isActivityLiving(ability)) {
                ability.terminateAbility();
            }
        }
    }

    public void setTitle(String title) {
        if (title != null && title.length() > 0) {
            mTvTitle.setText(title);
        } else {
            mTvTitle.setText("");
        }
    }

    @Override
    public void onComponentBoundToWindow(Component component) {
        if (!mIsRegister) {
            try {
                MatchingSkills matchingSkills = new MatchingSkills();
                matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BATTERY_CHANGED);
                CommonEventSubscribeInfo info = new CommonEventSubscribeInfo(matchingSkills);
                mBatteryReceiver = new BatteryReceiver(info, mIvBattery);
                CommonEventManager.subscribeCommonEvent(mBatteryReceiver);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mIsRegister = true;
        }
    }

    @Override
    public void onComponentUnboundFromWindow(Component component) {
        if (mIsRegister) {
            MatchingSkills matchingSkills = new MatchingSkills();
            CommonEventSubscribeInfo info = new CommonEventSubscribeInfo(matchingSkills);
            mBatteryReceiver = new BatteryReceiver(info, mIvBattery);
            try {
                CommonEventManager.unsubscribeCommonEvent(mBatteryReceiver);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mIsRegister = false;
        }
    }

    @Override
    public void attach(ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public Component getView() {
        return this;
    }

    @Override
    public void onVisibilityChanged(boolean isVisible, Animator anim) {
        // 只在全屏时才有效
        if (isVisible) {
            if (getVisibility() == HIDE) {
                mTvSysTime.setText(PlayerUtils.getCurrentSystemTime());
                setVisibility(VISIBLE);
                if (anim != null) {
                    onStart(anim);
                }
            }
        } else {
            if (getVisibility() == VISIBLE) {
                setVisibility(HIDE);
                if (anim != null) {
                    onStart(anim);
                }
            }
        }
        if (getVisibility() == VISIBLE) {
            if (mControlWrapper.isFullScreen()) {
                // 显示电量
                mIvBattery.setVisibility(VISIBLE);
                mTvSysTime.setVisibility(VISIBLE);
            } else {
                // 不显示电量
                mIvBattery.setVisibility(HIDE);
                mTvSysTime.setVisibility(HIDE);
            }
        }
    }

    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case ConstantKeys.CurrentState.STATE_IDLE:
            case ConstantKeys.CurrentState.STATE_START_ABORT:
            case ConstantKeys.CurrentState.STATE_PREPARING:
            case ConstantKeys.CurrentState.STATE_PREPARED:
            case ConstantKeys.CurrentState.STATE_ERROR:
            case ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING:
                setVisibility(HIDE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPlayerStateChanged(int playerState) {
        if (playerState == ConstantKeys.PlayMode.MODE_FULL_SCREEN) {
            if (mControlWrapper.isShowing() && !mControlWrapper.isLocked()) {
                setVisibility(VISIBLE);
                mTvSysTime.setText(PlayerUtils.getCurrentSystemTime());
            }
            mTvTitle.setSelected(true);
        } else {
            setVisibility(HIDE);
            mTvTitle.setSelected(false);
        }

        Ability ability = PlayerUtils.scanForActivity(mContext);
        if (ability != null && mControlWrapper.hasCutout()) {
            int orientation = ability.getDisplayOrientation();
            int cutoutHeight = mControlWrapper.getCutoutHeight();

            // 设置屏幕的变化是，标题的值。后期有需要在暴露给开发者设置
            if (orientation == 1) {
                // 切换成竖屏的时候调用
                mLlTitleContainer.setPadding(PlayerUtils.vp2px(mContext, 12),
                    PlayerUtils.vp2px(mContext, 10), PlayerUtils.vp2px(mContext, 12), 0);
            } else if (orientation == 0) {
                // 切换成横屏的时候调用
                mLlTitleContainer.setPadding(cutoutHeight, 0, PlayerUtils.vp2px(mContext, 12), 0);
            }
            /* else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                mLlTitleContainer.setPadding(0, 0, cutoutHeight, 0);
            }*/
            else {
                mLlTitleContainer.setPadding(PlayerUtils.vp2px(mContext, 12),
                    PlayerUtils.vp2px(mContext, 10), PlayerUtils.vp2px(mContext, 12), 0);
            }
        }
    }

    @Override
    public void setProgress(int duration, int position) {
    }

    @Override
    public void onLockStateChanged(boolean isLocked) {
        if (isLocked) {
            setVisibility(HIDE);
        } else {
            setVisibility(VISIBLE);
            mTvSysTime.setText(PlayerUtils.getCurrentSystemTime());
        }
    }

    @Override
    public void onStart(Animator animator) {
        animator.start();
    }

    @Override
    public void onStop(Animator animator) {
    }

    @Override
    public void onCancel(Animator animator) {
    }

    @Override
    public void onEnd(Animator animator) {
    }

    @Override
    public void onPause(Animator animator) {
    }

    @Override
    public void onResume(Animator animator) {
    }

    private static class BatteryReceiver extends CommonEventSubscriber {
        private Image pow;

        public BatteryReceiver(CommonEventSubscribeInfo subscribeInfo, Image pow) {
            super(subscribeInfo);
            this.pow = pow;
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent intent = commonEventData.getIntent();
            if (intent == null) {
                return;
            }
            int current = intent.getIntParam("level", 0); // 获得当前电量
            int total = intent.getIntParam("scale", 0); // 获得总电量
            /* int percent = current * 100 / total;
            pow.getImageElement().setLevel(percent);*/
        }
    }
}
